package com.gcxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcxy.constant.StringConst;
import com.gcxy.core.PageVO;
import com.gcxy.core.R;
import com.gcxy.dto.agency.AgencyDTO;
import com.gcxy.dto.agency.AgencyPageDTO;
import com.gcxy.entity.Agency;

import com.gcxy.entity.User;
import com.gcxy.enums.ResultCodeEnum;
import com.gcxy.mapper.AgencyMapper;
import com.gcxy.service.AgencyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.service.UserService;
import com.gcxy.utils.BeanCopyUtil;
import com.gcxy.utils.UserUtil;

import com.gcxy.vo.agency.AgencyAllListVO;
import com.gcxy.vo.agency.AgencyVO;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Huang先森
 * @since 2024-07-22
 */
@Service
public class AgencyServiceImpl extends ServiceImpl<AgencyMapper, Agency> implements AgencyService {

    @Resource
    private AgencyMapper agencyMapper;

    @Resource
    private UserService userService;

    @Override
    public R<?> insertAgency(AgencyDTO agencyDTO) {
        // 校验组织是否存在
        LambdaQueryWrapper<Agency> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Agency::getName, agencyDTO.getName());
        if (!ObjectUtils.isEmpty(getOne(queryWrapper))) {
            return R.Failed(ResultCodeEnum.EXIST_AGENCY.getCode(), ResultCodeEnum.EXIST_AGENCY.getMessage());
        }
        Agency agency = BeanCopyUtil.copy(agencyDTO, Agency.class);
        agency.setUpdater(UserUtil.getCurrentUser().getUsername());
        agency.setCreateTime(LocalDateTime.now());
        agency.setUpdateTime(LocalDateTime.now());
        int row = agencyMapper.insert(agency);
        if (row > 0) {
            return R.Success("新增组织成功");
        }
        return R.Failed("新增组织失败");
    }

    /**
     * 查询
     *
     * @param agencyPageDTO
     * @return
     */
    @Override
    public R<?> getAgencyPageByCondition(AgencyPageDTO agencyPageDTO) {
        // 开启分页
        Page<Agency> page = new Page<>(agencyPageDTO.getPageNo(), agencyPageDTO.getPageSize());
        // 定义查询条件
        LambdaQueryWrapper<Agency> queryWrapper = new LambdaQueryWrapper();
        queryWrapper
                .like(!ObjectUtils.isEmpty(agencyPageDTO.getName()), Agency::getName, agencyPageDTO.getName())
                .like(!ObjectUtils.isEmpty(agencyPageDTO.getId()), Agency::getId, agencyPageDTO.getId());
        Page<Agency> agencyPage = agencyMapper.selectPage(page, queryWrapper);
        PageVO<Agency> agencyPageVO = BeanCopyUtil.copy(agencyPage, PageVO.class);
        return R.Success(agencyPageVO);
    }

    /**
     * 更新组织
     *
     * @param agencyDTO
     * @return
     */
    @Override
    public R<?> updateAgency(AgencyDTO agencyDTO) {
        Agency agency = BeanCopyUtil.copy(agencyDTO, Agency.class);
        if (ObjectUtils.isEmpty(agencyDTO.getId())) {
            return R.Failed("id不能为空");
        }
        Agency agency1 = agencyMapper.selectById(agencyDTO.getId());

        if (ObjectUtils.isEmpty(agency1)) {
            return R.Failed(ResultCodeEnum.NOT_AGENCY.getCode(), ResultCodeEnum.NOT_AGENCY.getMessage());
        }
        agency.setId(agency1.getId());
        agency.setUpdateTime(LocalDateTime.now());
        agency.setUpdater(UserUtil.getCurrentUser().getUsername());
        int row = agencyMapper.updateById(agency);
        if (row > 0) {
            return R.Success("组织信息更新成功");
        }
        return R.Failed("组织信息更新失败");
    }

    /**
     * 删除组织
     *
     * @param id
     * @return
     */
    @Override
    public R<?> deleteAgencyById(Integer id) {
        //TODO 未添加删除限制， 组织下有账户的情况不能删除
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getAgencyId, id);
        List<User> userList = userService.list(queryWrapper);
        if (!ObjectUtils.isEmpty(userList)) {
            return R.Failed("组织有关联账户，无法删除！");
        }
        // 删除角色表中对应的数据
        int row = agencyMapper.deleteById(id);
        if (row > 0) {
            return R.Success("组织删除成功");
        }
        return R.Failed("组织删除失败");
    }

    /**
     * 根据组织名称获取组织信息
     *
     * @param name
     * @return
     */
    @Override
    public Agency getAgencyByName(String name) {
        LambdaQueryWrapper<Agency> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Agency::getName, name);
        Agency agency = agencyMapper.selectOne(queryWrapper);
        return agency;
    }

    /**
     * 获取所有组织信息
     * @return
     */
    @Override
    public List<AgencyAllListVO> getAgencyAllList() {
        //获取所有组织信息
        List<Agency> agencyList = list();
        AgencyVO agencyVO = userService.getUserInfo().getAgency();

        return agencyList.stream()
                .map(agency -> {
                    AgencyAllListVO agencyAllListVO = BeanCopyUtil.copy(agency, AgencyAllListVO.class);
                    if (!ObjectUtils.isEmpty(agencyVO) && agencyVO.getId().equals(agency.getId())) {
                        agencyAllListVO.setCurrentFlg(true);
                    }
                    return agencyAllListVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取能够执行周报任务的组织机构
     * @return
     */
    @Override
    public List<Agency> getHasWeeklyAgencyList() {
        LambdaQueryWrapper<Agency> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Agency::getHasWeeklyScheduled, StringConst.HAS_WEEKLY_SCHEDULED);
        return list(wrapper);
    }


}
